package com.idanchuang.support.etcache.remote.codec;

import java.io.*;

/**
 * Created on 2022/03/29.
 * @author yjy
 */
public class JavaValueCodec implements ValueCodec {

    private static final int INIT_BUF_SIZE = 256;

    @Override
    public byte[] encode(Object value) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(INIT_BUF_SIZE);
            try {
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(value);
                oos.flush();
                return bos.toByteArray();
            } finally {
                bos.reset();
            }
        } catch (IOException e) {
            throw new RuntimeException("Java encode error.", e);
        }
    }

    @Override
    public Object decode(byte[] bytes) {
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(in);
            return ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException("Java decode error.", e);
        }
    }
}
